import { Component, OnInit } from '@angular/core';
import { ShopWhereService } from './shopwhere.service';
import { ShopWhereDto } from './models';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.scss'],
  standalone: true,
  imports: [CommonModule, FormsModule]
})
export class ProductsComponent implements OnInit {
  // 商品数据
  shopWhere = {
    items: [] as ShopWhereDto[],
    totalCount: 0
  };
  
  // 分页参数
  list = {
    page: 1,
    pageSize: 10,
    skipCount: 0,
    maxResultCount: 10,
    sorting: '',
  };
  
  // 分页选项
  pageSizeOptions = [10, 25, 50, 100];
  currentPageSize = 10;
  inputPageNumber: number;
  maxPageCount = 1;
  visiblePageNumbers: number[] = [];
  
  // 搜索相关
  nameKeyword: string = '';
  isSearchMode: boolean = false;
  
  // 状态控制
  isLoading: boolean = false;
  hasError: boolean = false;
  errorMessage: string = '';
  
  constructor(private shopWhereService: ShopWhereService) {}

  ngOnInit(): void {
    console.log('ProductsComponent 初始化');
    this.loadData();
  }
  
  loadData(): void {
    console.log('开始加载数据...');
    this.isLoading = true;
    this.hasError = false;
    
    this.list.skipCount = (this.list.page - 1) * this.list.pageSize;
    this.list.maxResultCount = this.list.pageSize;
    
    const params = {
      skipCount: this.list.skipCount,
      maxResultCount: this.list.maxResultCount,
      sorting: this.list.sorting
    };
    
    console.log('请求参数:', params);
    
    if (this.isSearchMode && this.nameKeyword) {
      // 按名称搜索
      console.log('执行搜索，关键词:', this.nameKeyword);
      this.shopWhereService.searchByName(this.nameKeyword, params).subscribe({
        next: (response) => {
          console.log('搜索结果:', response);
          this.handleDataResponse(response);
        },
        error: (error) => {
          console.error('搜索错误:', error);
          this.handleError(error);
        }
      });
    } else {
      // 获取全部列表
      console.log('获取全部列表');
      this.shopWhereService.getList(params).subscribe({
        next: (response) => {
          console.log('获取列表结果:', response);
          this.handleDataResponse(response);
        },
        error: (error) => {
          console.error('获取列表错误:', error);
          this.handleError(error);
        }
      });
    }
  }
  
  loadDataDirectly(): void {
    console.log('直接从API加载数据...');
    this.isLoading = true;
    this.hasError = false;
    
    const params = {
      skipCount: this.list.skipCount,
      maxResultCount: this.list.maxResultCount,
      sorting: this.list.sorting
    };
    
    console.log('直接请求参数:', params);
    
    this.shopWhereService.getListDirect(params).subscribe({
      next: (response) => {
        console.log('直接请求结果:', response);
        this.handleDataResponse(response);
      },
      error: (error) => {
        console.error('直接请求错误:', error);
        this.handleError(error);
      }
    });
  }
  
  handleDataResponse(response: any): void {
    this.shopWhere = response;
    console.log('处理数据响应，总数:', this.shopWhere.totalCount, '条目数:', this.shopWhere.items?.length);
    this.calculatePagination();
    this.isLoading = false;
  }
  
  handleError(error: any): void {
    this.hasError = true;
    console.error('错误详情:', error);
    
    if (error.status === 404) {
      this.errorMessage = '找不到API端点，请检查后端服务是否正确配置';
    } else if (error.status === 0) {
      this.errorMessage = '无法连接到服务器，请检查网络连接或后端服务是否运行';
    } else if (error.status === 401) {
      this.errorMessage = '未授权访问，请检查权限配置';
    } else if (error.status === 403) {
      this.errorMessage = '禁止访问，请检查权限配置';
    } else if (error.status === 500) {
      this.errorMessage = '服务器内部错误: ' + (error.error?.message || error.message || '未知错误');
    } else {
      this.errorMessage = error.message || error.error?.message || '加载数据失败，请稍后再试';
    }
    
    this.isLoading = false;
  }
  
  calculatePagination(): void {
    // 计算最大页数
    this.maxPageCount = Math.ceil(this.shopWhere.totalCount / this.list.pageSize);
    if (this.maxPageCount < 1) this.maxPageCount = 1;
    
    // 生成可见页码列表
    this.visiblePageNumbers = [];
    let startPage = Math.max(1, this.list.page - 2);
    let endPage = Math.min(this.maxPageCount, startPage + 4);
    
    if (endPage - startPage < 4) {
      startPage = Math.max(1, endPage - 4);
    }
    
    for (let i = startPage; i <= endPage; i++) {
      this.visiblePageNumbers.push(i);
    }
    
    console.log('分页信息:', {
      当前页: this.list.page,
      总页数: this.maxPageCount,
      可见页码: this.visiblePageNumbers
    });
  }
  
  goToPage(page: number): void {
    if (page < 1 || page > this.maxPageCount || page === this.list.page) return;
    
    console.log('跳转到页:', page);
    this.list.page = page;
    this.loadData();
  }
  
  onPageSizeChange(size: number): void {
    if (this.list.pageSize === size) return;
    
    console.log('改变每页大小:', size);
    this.list.pageSize = size;
    this.list.page = 1; // 改变页大小后回到第一页
    this.loadData();
  }
  
  onPageInputChange(event: any): void {
    const value = parseInt(event.target.value);
    if (value < 1) {
      this.inputPageNumber = 1;
    } else if (value > this.maxPageCount) {
      this.inputPageNumber = this.maxPageCount;
    }
  }
  
  onPageInputKeyUp(event: KeyboardEvent): void {
    if (event.key === 'Enter') {
      this.goToPage(this.inputPageNumber);
    }
  }
  
  searchProducts(): void {
    if (!this.nameKeyword || this.nameKeyword.trim() === '') {
      if (this.isSearchMode) {
        this.resetSearch();
      }
      return;
    }
    
    console.log('执行搜索，关键词:', this.nameKeyword);
    this.isSearchMode = true;
    this.list.page = 1; // 搜索时回到第一页
    this.loadData();
  }
  
  resetSearch(): void {
    console.log('重置搜索');
    this.nameKeyword = '';
    this.isSearchMode = false;
    this.list.page = 1;
    this.loadData();
  }
  
  retryLoad(): void {
    console.log('重试加载数据');
    this.loadData();
  }
} 